import { useEffect, useState, useRef } from 'react';
import { message } from 'antd';
import { ModalForm, ProFormDigit, ProFormRadio } from '@ant-design/pro-components';
import styles from './index.module.less';
import { formatNum, isSuccess, jingDuNum, orderText } from '@/utils';
import { contractAccount, submitOrderApi, tickersApi } from '@/api';
import { handleOrderTypePrice } from '@/utils/helper';
import PubSub from 'pubsub-js';

export default function JianCangModal({ open, setOpen, formData, reload }: any) {
  const [newPrice, setNewPrice] = useState<any>();
  const formRef: any = useRef('');
  const [hidePrice, setHidePrice] = useState(formData?.type === 'shijia');
  const [chiCangSize, setChiCangSize] = useState(0);
  const [unit] = useState(formData?.contract.split('_')[0]);
  const [chengShu] = useState(formData?.contractInfo?.quanto_multiplier);

  const types = [
    { label: '限价平仓', value: 'xian' },
    { label: '市价平仓', value: 'shijia' },
  ];

  useEffect(() => {
    if (open) initData();
    // console.log('formData: JianCangModal', formData);
  }, [open]);

  // 初始化数据
  const initData = () => {
    const _chiCangSize = Math.abs(+jingDuNum(formData?.size).times(jingDuNum(chengShu)));
    setChiCangSize(_chiCangSize);
    formRef?.current?.resetFields();
    if (formData?.id) {
      formRef?.current?.setFieldsValue({
        type: formData?.type,
        size: _chiCangSize,
      });
    }
    getContractTickers();
  };

  // 合约行情-单个
  async function getContractTickers() {
    const val: any = await tickersApi({ contract: formData?.contract });
    const res = val?.[0];
    setNewPrice(formatNum(res?.last));
    formRef?.current?.setFieldsValue({
      price: res?.last,
    });
  }

  // 账号信息
  async function getAccount() {
    const res: any = await contractAccount();
    if (isSuccess(res)) {
      return res?.data;
    } else {
      return false;
    }
  }

  // 提交
  const submit = async () => {
    // 判断是多仓还是单仓模式
    // const isDuoCang = (await getAccount())?.in_dual_mode;
    let value = await formRef?.current?.validateFieldsReturnFormatValue();
    let params: any = {
      contract: formData?.contract,
      text: orderText,
      reduce_only: true,
      price: value?.price,
      stp_act: '-',
    };
    // 处理数量
    const _size = +jingDuNum(value?.size).div(jingDuNum(chengShu));
    params.size = (formData?.size > 0 ? -1 : 1) * _size;
    // 下单时处理限价、市价的参数
    const orderTypePriceRes = handleOrderTypePrice(value.type, value.price);
    params = { ...params, ...orderTypePriceRes };
    const res: any = await submitOrderApi(params);
    console.log('一键清仓');
    if (!isSuccess(res)) return;
    PubSub.publish('updataKeYongYuE', true);
    message.success('成功');
    reload();
    setOpen(false);
  };

  function onValuesChange(e: any) {
    if (e?.type) setHidePrice(e?.type === 'shijia');
  }

  return (
    <ModalForm
      title={`平仓`}
      formRef={formRef}
      open={open}
      layout="horizontal"
      onFinish={submit}
      onOpenChange={setOpen}
      labelCol={{ span: 4 }}
      width={500}
      onValuesChange={onValuesChange}
    >
      <br />
      <div className={`${styles.JianCangModal}`}>
        <div className={`${styles.row}`}>
          <div className={`${styles.label}`}>最新价格：</div>
          <div className={`${styles.val}`}>{newPrice} USDT</div>
        </div>
        <div className={`${styles.row}`}>
          <div className={`${styles.label}`}>开仓均价：</div>
          <div className={`${styles.val}`}>{formatNum(formData?.entry_price)} USDT</div>
        </div>
        <div className={`${styles.row}`}>
          <div className={`${styles.label}`}>持仓数量：</div>
          <div className={`${styles.val}`}>
            {chiCangSize} {unit}
          </div>
        </div>
      </div>
      <ProFormRadio.Group name="type" label="类型" options={types} />
      {!hidePrice && (
        <ProFormDigit
          name="price"
          label="价格"
          rules={[{ required: true }]}
          fieldProps={{
            suffix: 'USDT',
          }}
        />
      )}
      <ProFormDigit
        name="size"
        label="数量"
        rules={[{ required: true }]}
        max={chiCangSize}
        fieldProps={{
          suffix: unit,
        }}
      />
    </ModalForm>
  );
}
